package cn.dkdoo.utils.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Created by TJS on 2019/3/11
 */
@Component
public class DkdSpringUtils implements ApplicationContextAware {
    private static final Logger LOGGER = LoggerFactory.getLogger(DkdSpringUtils.class);
    private static ApplicationContext APPLICATION_CONTEXT;

    /**
     * 设置spring上下文 bean前置处理器调用
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        LOGGER.debug("ApplicationContext registed-->{}", applicationContext);
        APPLICATION_CONTEXT = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return APPLICATION_CONTEXT;
    }

    /**
     * 注意 bean name默认 = 类名(首字母小写)
     * 例如: A8sClusterDao = getBean("a8sClusterDao")
     *
     * @param beanName
     * @return
     * @throws BeansException
     */
    public static <T> T getBeanByBeanName(String beanName) {
        try {
            return (T) DkdSpringUtils.getApplicationContext().getBean(beanName);
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage());
            return null;
        }
    }


    /**
     * 根据类名获取到bean
     *
     * @param <T>
     * @param clazz
     * @return
     * @throws BeansException
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBeanByClass(Class<T> clazz) throws BeansException {
        try {
            return (T) DkdSpringUtils.getApplicationContext().getBean(clazz);
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage());
            return null;
        }
    }
}